package cn.serenedream.housedecoration.serivce;

import cn.hutool.core.util.IdUtil;
import cn.serenedream.housedecoration.dao.UserRepository;
import cn.serenedream.housedecoration.dto.UserDTO;
import cn.serenedream.housedecoration.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    UserRepository userRepository;

    public Long count() {
        return userRepository.count();
    }

    public Page<User> list(Integer currentPage, Integer pageSize) {
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return userRepository.findAll(pageable);
    }

    public void save(UserDTO userDTO) {
        User user = new User();

        Optional<User> flax = userRepository.findById(safeParseLong(userDTO.getId(), 0L));

        if (flax.isEmpty()){
            user.setId(IdUtil.getSnowflakeNextId());
        } else {
            user.setId(Long.parseLong(userDTO.getId()));
        }

        user.setName(userDTO.getName());
        user.setAddress(userDTO.getAddress());
        user.setMobile(safeParseLong(userDTO.getMobile(), 0L));
        user.setSpareMobile(safeParseLong(userDTO.getSpareMobile(), 0L));

        userRepository.save(user);
    }

    public Long safeParseLong(String value, Long defaultValue) {
        if (value == null || value.isBlank()) {
            return defaultValue;
        }
        try {
            return Long.parseLong(value.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public void delete(String id) {
        userRepository.deleteById(Long.parseLong(id));
    }

    public Page<User> findByName(Integer currentPage, Integer pageSize, String name) {
        Pageable pageable = PageRequest.of(currentPage, pageSize, Sort.by("id").descending());
        return userRepository.findByName(name, pageable);
    }

    public User findById(String userId) {
        BigDecimal bigDecimal = new BigDecimal(userId);
        return userRepository.findById(bigDecimal.longValue()).get();
    }

    public List<User> findAll() {
        return userRepository.findAll();
    }
}
